import $ from 'jquery'
import Od from '../cls/Od'
import od from './components'
import {camel2kabab,randstr} from "../util"

export function init_ui_sortable(project){
    $(".sortable" ).sortable({
        connectWidth:".sortable",
        handle:'.drag',
        update:function(e,t) {
            project.scene = "view"
            update_ui(t,project)
        }
    })
    $( ".views-table .draggable" ).draggable({
        connectToSortable: ".sortable",
        helper: "clone",
        handle:".drag",
    })
}
function get_parent_view($ele, project) {
    if($ele.attr("id") === "editor") {
        return null
    }
    if($ele.parent().hasClass("vm")) {
        return project.od_map.get($ele.parent().attr("id"))
    }
    return get_parent_view($ele.parent(),project)
}
function replaceT(ele, project){
    let $ele = $(ele)
    if(!$ele.hasClass("vm") && $ele.find(".vm").length === 0) {
        return ele
    }

    if($ele.hasClass("vm")) {
        let id = $ele.attr("id")
        let od = project.od_map.get(id)
        od.build($ele)//重建组件
    }
    let childs = $ele.children()
    for(let i = 0;i < childs.length;i++) {
        let c = childs[i]
        replaceT(c, project)
    }
}
function reset(project) {
    let dv = $("<div></div>")
    dv.html($("#editor").html())
    let childs = dv.children()
    for(let i = 0;i < childs.length;i++) {
        let c = childs[i]
        replaceT(c, project)
    }
    project.manager.current.file.write(dv.html())

}
function update_ui(t, project) {
    let target_ele = t.item[0]
    let $ele = $(target_ele)
    //判断当前节点是否为Vue节点
    if($ele.hasClass("vm") &&  $ele.attr("id") === undefined){//如果当前为Vue组件，则注册该节点到组件表中
        let ctrl = $ele.attr("action-view")
        let key = randstr()
        $ele.attr("id", key)
        $ele.find(".slot").attr("target-view",key)
        let o = new Od(key, od[ctrl].templates[0].name,od[ctrl],$ele.clone())
        if(od[ctrl]['view']) {
            let oo = od[ctrl]['view'][o.name]
            for(let kk in oo) {
                $ele.find(".vm-view").css(camel2kabab(kk),oo[kk])
            }
        }
        project.od_map.set(key, o)
    }
    $ele.addClass("show")
    //向上查找上级的Od，diff
    let last_ele = get_parent_view($ele, project)
    if(last_ele === null) {
        make_vue(project)
        return
    }
    //调用当前Od的diff计算当前节点的差值
    last_ele.diff()
    make_vue(project)
}
export function make_vue(project) {
    reset(project)
    let component = project.manager.current.mkView()
    $("#editor").html(project.manager.current.file.content)
    component.el = "#editor"
    new window.Vue(component)
    $(".sortable" ).sortable({
        connectWidth:".sortable",
        handle:'.drag',
        stop:function(e,ui0) {
            update_ui(ui0, project)
        }
    })
    $(".views-table .draggable").draggable({
        connectToSortable: ".sortable",
        helper: "clone",
        handle:".drag",
        stop:()=>{}
    })
}


//监听属性修改
export function listen_props_change(project) {
    let prop_var_re = /^\{\{[\s\S]+\}\}$/
    let prop_var_pick_re = /^\{\{([\s\S]+)\}\}$/
    $("body").on("change","[prop]",(e) => {
        let $e = $(e.target)
        let prop = $e.attr('prop')
        let propTarget = $e.attr('prop-target')
        let val = $e.val()
        let id = $(project.cur_dom).attr("id")
        let o = project.od_map.get(id)
        if(!o) return
        //TODO:判断val是值还是变量
        if(prop_var_re.test(val)) {
            let _var_re = val.match(prop_var_pick_re)
            let _var = _var_re[1]
            //TODO:判断val是否在变量中
            if(project.manager.current.data[_var] == undefined){
                alert(_var + "未在变量中定义")
                return
            }
            if(prop != "v-model" && prop != "v-if" && prop != "v-for"){
                o.setProp(":" + prop,_var,propTarget)
            }else {
                o.setProp(prop,val,propTarget)
            }
        }else {
            o.setProp(prop,val,propTarget)
        }
        o.diff()
        make_vue(project)
    })
}

export function listen_content_change(e, project) {
    //向上查找上级的Od，diff
    let last_ele = get_parent_view($(e.target),project)
    if(last_ele === null) {
        make_vue(project)
        return
    }
    //调用当前Od的diff计算当前节点的差值
    last_ele.diff()
    make_vue(project)
}

export function listen_data_change(e,project) {
    //TODO:遍历所有的输入组建数据对象
    let data = {}
    let items = $("#vuedata").find(".data-box-item")
    for(let i = 0;i < items.length;i++){
        let _val = items[i]
        let label = $(_val).find(".data-box-label input").val()
        let val = $(_val).find(".data-box-value input").val()
        data[label] = new Function("return " + val)()
    }
    project.manager.current.data = data
    make_vue(project)
}